package com.book.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.book.items.composite.AbstractProductItem;
import com.book.items.composite.ProductComposite;
import com.book.mapper.ProductItemMapper;
import com.book.pojo.ProductItem;
import com.book.service.ProductItemService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class ProductItemServiceImpl extends ServiceImpl<ProductItemMapper, ProductItem> implements ProductItemService {



    @Autowired
    StringRedisTemplate redisTemplate;

    /**
     * 获取商品类目信息
     *
     * @return
     */
    public ProductComposite fetchAllItems() {
       /* String stringItems = redisTemplate.opsForValue().get("items");
        // 如果缓存中存在
        if (StringUtils.isNotBlank(stringItems)) {
            return JSON.parseObject(stringItems, ProductComposite.class);
        }*/
        // 不存在
        List<ProductItem> fetchDbItems = list();

        ProductComposite items = generateProductTree(fetchDbItems);
        if (null == items) {
            throw new UnsupportedOperationException("Product items should not be empty in db");
        }
        // 将商品类目存到redis
//        redisTemplate.opsForValue().set("items", JSON.toJSONString(items));
        return items;
    }

    private ProductComposite generateProductTree(List<ProductItem> fetchDbItems) {
        List<ProductComposite> composites = fetchDbItems.stream().map(productItem -> {
            ProductComposite composite = new ProductComposite();
            BeanUtils.copyProperties(productItem, composite);
            return composite;
        }).collect(Collectors.toList());

        Map<Integer, List<ProductComposite>> groupingList = composites.stream().collect(Collectors.groupingBy(ProductComposite::getPid));

        composites.stream().forEach(item -> {
            List<ProductComposite> productComposites = groupingList.get(item.getId());
            item.setChild(CollectionUtils.isEmpty(productComposites) ?
                    Collections.EMPTY_LIST : productComposites.stream().map(x -> (AbstractProductItem) x).collect(Collectors.toList()));

        });
        /**
         * 这里封装了很多🌲，但是 get（0）是最完整的那条🌲
         */
        return composites.size() == 0 ? null : composites.get(0);
    }


}